***********************************************************************************
********"Macroprudential Regulation, Quantitative Easing, and Bank Lending"********
***********************************************************************************
* This file produces a dataset with the book value of government securities 
* in different portofolios and with different maturities (>=5 years, <5 years,
* >= 2 years, all maturities)
***********************************************************************************
***********************************************************************************


*==================================================================================
**# Bookmark (input)
clear *
use $inputdirectory/portfolioover, clear
rename *, lower

tostring(dat), replace
gen xxx=date(dat, "YMD")
gen year=year(xxx)
gen time=mofd(xxx)
drop xxx dat

tostring(date_mat), replace
gen xxx=date(date_mat, "YMD")
gen mat=mofd(xxx)
drop xxx date_mat

format time %tm
format mat %tm

gen monthtom=mat-time

foreach cycle in 1 2 3 4 {
preserve
if `cycle'==1 {
	keep if monthtom>=60
	}
if `cycle'==2 {
	keep if monthtom<60
	drop if monthtom<0
	}
if `cycle'==3 {
	keep if monthtom>=24
	}
if `cycle'==4 {
	drop if monthtom<0
	}

replace book=-book if (portaf_contab==508|portaf_contab==409)&time>=tm(2018m1)
gen portfolio=.
replace portfolio=1 if inlist(portaf_contab,403,405,406)&time>=tm(2018m1)
replace portfolio=2 if inlist(portaf_contab,407)&time>=tm(2018m1)
replace portfolio=3 if inlist(portaf_contab,401,402,0,408)&time>=tm(2018m1)

replace book=-book if (portaf_contab==508|portaf_contab==509)&time<tm(2018m1)
replace portfolio=1 if inlist(portaf_contab,504,505,506,512)&time<tm(2018m1)
replace portfolio=2 if inlist(portaf_contab,503)&time<tm(2018m1)
replace portfolio=3 if inlist(portaf_contab,501,502,0,508)&time<tm(2018m1)

merge m:1 bankid year using $inputdirectory/INB_typesmonpol, keepus(type)
keep if _merge==3
drop _merge

merge m:1 bankid year using $inputdirectory/INB_grumonpol, keepus(gru)
keep if _merge!=2
drop _merge
replace gru=bankid if gru==.

gen xxx=type if bankid==gru
egen grutype=max(xxx), by(gru)
replace grutype=10 if grutype==.
drop xxx
keep if grutype==10

drop bankid
rename gru bankid

collapse (sum) book, by(bankid portfolio time)
compress

drop if portfolio==.
reshape wide book, i(bankid time) j(portfolio)

**# Bookmark (saving dataset - book value of government securities)
if `cycle'==1 {
	save $inputdirectory/INB_isinmonpol, replace
	}
if `cycle'==2 {
	rename book1 book1m5
	rename book2 book2m5
	rename book3 book3m5
	save $inputdirectory/INB_isinmonpol`cycle', replace
	}
if `cycle'==3 {
	rename book1 book1p2
	rename book2 book2p2
	rename book3 book3p2
	save $inputdirectory/INB_isinmonpol`cycle', replace
	}
if `cycle'==4 {
	rename book1 book1all
	rename book2 book2all
	rename book3 book3all
	save $inputdirectory/INB_isinmonpol`cycle', replace
	}
	
restore
}

